package cn.hywx.convert;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.document.DefaultDocumentFormatRegistry;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
/**
 * Convert tools for
 * office to pdf
 * pdf to swf
 * 
 * @author all3n
 *
 */
public class Convert {

	public static int DEFAULT_PORT = 8100;

	public static String DEFAULT_HOST = "127.0.0.1";

	public DefaultDocumentFormatRegistry formatReg = null;

	public DefaultOfficeManagerConfiguration officeMgrConf = null;

	public OfficeManager officeMgr = null;

	public Convert() {
		formatReg = new DefaultDocumentFormatRegistry();
		officeMgrConf = new DefaultOfficeManagerConfiguration();
		// officeMgrConf.setOfficeHome(officeHome);
		this.startService();
	}

	public boolean isServiceStart() {
		Socket socket = null;
		try {
			socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public void startService() {
		try {
			officeMgrConf.setPortNumber(DEFAULT_PORT);
			officeMgrConf.setTaskExecutionTimeout(1000 * 60 * 5L);
			officeMgrConf.setTaskQueueTimeout(1000 * 60 * 60 * 24L);

			officeMgr = officeMgrConf.buildOfficeManager();
			// System.out.println(isServiceStart());
			// if(!isServiceStart()){
			officeMgr.start();
			// }
			System.out.println("service start success");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void stopService() {
		System.out.println("stop service ...");
		if (officeMgr != null) {
			officeMgr.stop();
		}
	}

	/**
	 * 执行前，请启动openoffice服务 进入$OO_HOME\program下 执行soffice -headless
	 * -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
	 */
	public void office2Pdf(String sourceUrl, String targetUrl) throws Exception {
		File sourceFile = new File(sourceUrl);
		File targetFile = new File(targetUrl);
		// 获得文件格式

		try {
			OfficeDocumentConverter converter = new OfficeDocumentConverter(
					officeMgr);
			converter.convert(sourceFile, targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	public int pdf2Swf(String pdfFileName, String destFileName) {
		if (null != pdfFileName && pdfFileName.length() > 0) {

			String fileExt = "";

			StringBuffer command = new StringBuffer();

			Process pro;

			BufferedReader buffer;

			int dotIndex = -1;
			if ((dotIndex = pdfFileName.lastIndexOf(".")) > 0) {
				fileExt = pdfFileName.substring(dotIndex + 1, pdfFileName.length())
						.toLowerCase();
			} else {
				fileExt = "txt";
			}

			try {
				File file = new File(pdfFileName);
				if (!file.exists()) {
					return -1;
				} else if (!fileExt.equals("pdf")) {
					return -2;
				} else {
					 command.append("pdf2swf")
							.append(" -o ")
							.append(destFileName)
							.append(" -T 9 -z -t -f ")
							.append(" -Q 300 " )
							.append(pdfFileName).append(" -s languagedir=")
							.append("/usr/share/xpdf/chinese-simplified")
							.append(" -s flashversion=9");
					System.out.println(command.toString()); 
					pro = Runtime.getRuntime().exec(command.toString());
					
					
					
					buffer = new BufferedReader(new InputStreamReader(
							pro.getInputStream()));
					String temp;
					while ((temp = buffer.readLine()) != null){
						System.out.println(temp);
					}

					int rtstate = pro.waitFor();
					
//					System.out.println("rtstate:"+rtstate);
					
					
					// if (0 == rtstate) {
					// // System.out.println("rm file start");
					// StringBuffer rmcommand = new StringBuffer();
					// rmcommand.append("rm -rf ").append(fileName);
					// // System.out.println(rmcommand.toString());
					// pro = Runtime.getRuntime().exec(rmcommand.toString());
					// buffer = new BufferedReader(new InputStreamReader(
					// pro.getInputStream()));
					// while (buffer.readLine() != null)
					// ;
					//
					// int rmstauts = pro.waitFor();
					// // System.out.println(rmstauts);
					// return rmstauts;
					// }
					return rtstate;
				}

			} catch (Exception e) {
				System.out.println(e.getMessage());
				return -3;
			} finally {
				command = null;
				pro = null;
				buffer = null;
			}
		} else {
			return 1;
		}
	}

	public static void main(String[] args) {
		System.out.println("begin...");
		Convert con = new Convert();
		String officeFile = "/home/all3n/convert/2.odt";
		String pdfFile = "/home/all3n/convert/2.pdf";
		try {
			con.office2Pdf(officeFile,pdfFile);
			int res = con.pdf2Swf(pdfFile, "/home/all3n/convert/2.swf");
		} catch (Exception e) {
			e.printStackTrace();
		}
		con.stopService();
		System.out.println("ok!!!");
	}
}
